package easy_dfa

import (
	"gitee.com/eeany/readbyline"
	"github.com/EverythingMe/inbloom/go/inbloom"
)

//保存单个匹配到的关键字
type Keyword struct {
	keyword string
	isEnd bool
	isNil bool
}

func NewKeyword(keyword1 string, isEnd bool) *Keyword {
	return &Keyword{keyword: keyword1, isEnd: isEnd,isNil: true}
}


//1、单词匹配
type Keywords struct {
	Keywords []Keyword            //关键字列表
	bloom    *inbloom.BloomFilter //过滤器
	maxLen   int                  //最大的关键字的长度
}

func (receiver Keywords) FindWords(src string) []string {
	re :=[]string{}
	strRune :=  []rune(src)
	for i := 0; i < len(strRune); i++ {
		re1 :=receiver.AddChar(string(strRune[i]))
		if len(re1)>0{
			re=append(re, re1[0])
		}
	}
	return re
}
//添加字符
func (receiver Keywords) AddChar(oneChar string)  []string{
	var (
		re       []string
		isAddNew bool
	)
	isAddNew=false
	for i := 0; i < len(receiver.Keywords); i++ {
		if !receiver.Keywords[i].isNil{
			oneItem :=receiver.Keywords[i]
			//如果检查到新增加的 字符串存在于关键字列表中。
			if receiver.bloom.Contains(oneItem.keyword+oneChar) {
				re  = append(re, oneItem.keyword+oneChar)
				oneItem.isEnd=true
				receiver.Keywords[i]=*NewKeyword("",false)
			}else{
				//添加字符长度
				oneItem.keyword=oneItem.keyword+oneChar
				if len(oneItem.keyword)>receiver.maxLen {
					receiver.Keywords[i]=*NewKeyword("",false)
				}else {
					receiver.Keywords[i]=oneItem
				}
			}
		}else {
			//每个字符单独增加一个新的
			if !isAddNew {
				receiver.Keywords[i]=*NewKeyword(oneChar,false)
				receiver.Keywords[i].isNil=false
				isAddNew=true
			}
		}
	}
	//最大长度出现异常。
	if !isAddNew {
		receiver.maxLen=receiver.maxLen+1
		receiver.Keywords =append(receiver.Keywords, *NewKeyword(oneChar,false))
	}
	return re
}

func NewKeywords(bloom *inbloom.BloomFilter, maxLen int) *Keywords {
	re:= &Keywords{bloom: bloom, maxLen: maxLen}
	for i := 0; i < maxLen; i++ {
		re.Keywords =append(re.Keywords, *NewKeyword("",false))
	}
	return re
}

func NewKeywordsByFile(path string) *Keywords {
	maxLeng:=0
	reString:=readbyline.ReadLine(path)
	bloom, _ := inbloom.NewFilter(len(reString)*5, 0.01)
	for i := 0; i < len(reString); i++ {
		bloom.Add(reString[i])
		if len(reString[i])>maxLeng {
			maxLeng=len(reString[i])
		}
	}
	kes:= NewKeywords(bloom,maxLeng)
	return  kes
}


